package com.cloudbroker.bcs.platform.dav.middle.util;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudbroker.bcs.platform.dav.common.util.CacheHelper;

/**
 * Jedis实现分布式锁
 * 
 */
public class DistributionLock {
    
    private static final Logger logger = LoggerFactory.getLogger(DistributionLock.class);
    
    /**
     * 获取分布式锁
     * 
     * @param lockName
     *            竞争获取锁key
     * @param acquireTimeoutInMS
     *            获取锁超时时间
     * @param lockTimeoutInMS
     *            锁的超时时间
     * @return 获取锁标识
     */
    public static String acquireLockWithTimeout(String lockName, long acquireTimeoutInMS, long lockTimeoutInMS) {
        String retIdentifier = null;
        try {
            String identifier = UUID.randomUUID().toString();
            String lockKey = "lock:" + lockName;
            int lockExpire = (int) (lockTimeoutInMS / 1000);
            
            long end = System.currentTimeMillis() + acquireTimeoutInMS;
            while (System.currentTimeMillis() < end) {
                if (CacheHelper.setnx(lockKey, identifier) == 1) {
                    CacheHelper.expire(lockKey, lockExpire);
                    retIdentifier = identifier;
                }
                if (StringUtils.isNotBlank(retIdentifier)) {
                    break;
                }
                if (CacheHelper.ttl(lockKey) == -1) {
                    CacheHelper.expire(lockKey, lockExpire);
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
        } catch (Exception e) {
            logger.error("get redis mutex error:" + e);
        }
        return retIdentifier;
    }
    
    /**
     * 释放锁
     * @param lockName 竞争获取锁key
     * @param identifier 释放锁标识
     * @return
     */
    public static void releaseLock(String lockName, String identifier) {
        CacheHelper cacheHelper = null;
        try {
            if (StringUtils.isBlank(identifier) || StringUtils.isBlank(lockName)) {
                return;
            }
            cacheHelper = CacheHelper.getInstance();
            String lockKey = "lock:" + lockName;
            if(cacheHelper.get(lockKey) != null && cacheHelper.get(lockKey).equals(identifier)){
                cacheHelper.delete(lockKey);
            }
        } catch (Exception e) {
            logger.error("release redis mutex error:" + e);
        }
    }
    
}
